package com.example.utils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class RequestUtil<T> {

    /**
     * 获取请求参数值，通过反射调用对象的set方法赋值。调用例子RequestUtil.getParameters(request, new User())
     *
     * @param request
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T getParameters(HttpServletRequest request, T t) {

        Map<String, String> paraMap = getParameterMap(request);

        Method[] methods = t.getClass().getMethods();
        String methodName;
        for (Method method : methods) {
            methodName = method.getName();
            if (methodName.startsWith("set")) {
                String paraKey = firstLowercase(methodName.substring(3));//获取set开头方法，去掉set，并将首字母变小写
                if (paraMap.containsKey(paraKey)) {
                    System.out.println("参数值->" + paraKey + ":" + paraMap.get(paraKey));
                    String paraValueString = paraMap.get(paraKey);
                    Object paraValueObject = null;
                    Class<?> type = method.getParameterTypes()[0];
                    if (type == String.class) {
                        paraValueObject = paraValueString;
                    } else if (type == Date.class) {
                        //可根据需求修改
                        paraValueObject = stringToDate(paraValueString, "yyyy-MM-dd HH:mm:ss");
                    } else if (type == int.class || type == Integer.class) {
                        paraValueObject = Integer.valueOf(paraValueString);
                    } else if (type == double.class || type == Double.class) {
                        paraValueObject = Double.valueOf(paraValueString);
                    } else if (type == float.class || type == Float.class) {
                        paraValueObject = Float.valueOf(paraValueString);
                    }

                    try {
                        method.invoke(t, paraValueObject); //执行set方法
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        System.out.println("执行失败:" + method.getName());
                        e.printStackTrace();
                    }
                }
            }
        }
        return t;
    }

    public static Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        Set<String> keySet = map.keySet();
        Iterator<String> iterator = keySet.iterator();
        Map<String, String> paraMap = new HashMap<>();
        //保存参数到Map
        while (iterator.hasNext()) {
            String keyTemp = iterator.next();
            if (map.get(keyTemp).length == 1) {
                paraMap.put(keyTemp, map.get(keyTemp)[0]);
            }
        }
        return paraMap;
    }

    private static String firstLowercase(String s) {
        char[] chars = s.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    /**
     * @param strDate
     * @param pattern 格式如:yyyy-MM-dd HH:mm:ss:SSS 年月日时分秒毫秒
     * @return
     */
    private static Date stringToDate(String strDate, String pattern) {
        Date date = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        try {
            date = simpleDateFormat.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

}
